package com.xinyuan.trade.Dialog;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

import com.tencent.connect.auth.QQAuth;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXTextObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.open.t.Weibo;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.xinyuan.trade.R;
import com.xinyuan.trade.XYApplication;
import com.xinyuan.trade.Activity.BaseActivity;
import com.xinyuan.trade.Utils.Constants;
import com.xinyuan.trade.Widght.Toast;

/**
 * 分享对话框
 * @author 烨
 *
 */
public class ShareDialog implements OnClickListener {
	
	private IWXAPI iwxapi;
	private Tencent mTencent;
	private final int TIMELINE_SUPPORTED_VERSION = 0x21020001;
	public String msg;
	private Dialog dialog;
	private BaseActivity activity;
	private QQShare mQQShare = null;
	private static QQAuth mQQAuth = null;
	private Weibo mWeibo = null;
	
	public ShareDialog(BaseActivity activity, String msg) {
		this.activity = activity;
		this.msg = msg;
		
		iwxapi = WXAPIFactory.createWXAPI(XYApplication.getContext(),
				APP_ID, true);
		iwxapi.registerApp(APP_ID);
		
//		// Tencent类是SDK的主要实现类，开发者可通过Tencent类访问腾讯开放的OpenAPI。
//		// 其中APP_ID是分配给第三方应用的appid，类型为String。
		mTencent = Tencent.createInstance(Constants.Tencent_APP_ID, activity);
		mQQAuth = QQAuth.createInstance(Constants.Tencent_APP_ID, activity);
		mQQShare = new QQShare(activity, mQQAuth.getQQToken());
		mWeibo = new Weibo(activity, mQQAuth.getQQToken());
		
		LayoutInflater mInflater = (LayoutInflater) activity
				.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		View view = mInflater.inflate(R.layout.dlg_share, null);
		
		LinearLayout item_weixin = (LinearLayout) view.findViewById(R.id.item_weixin);
		LinearLayout item_qq = (LinearLayout) view.findViewById(R.id.item_qq);
		LinearLayout item_qqzone = (LinearLayout) view.findViewById(R.id.item_qqzone);
		LinearLayout item_friends = (LinearLayout) view.findViewById(R.id.item_friends);
		LinearLayout item_weibo = (LinearLayout) view.findViewById(R.id.item_weibo);
		Button btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
		item_weixin.setOnClickListener(this);
		item_qq.setOnClickListener(this);
		item_qqzone.setOnClickListener(this);
		item_friends.setOnClickListener(this);
		item_weibo.setOnClickListener(this);
		btn_cancel.setOnClickListener(this);
		
		dialog = new Dialog(activity, R.style.ShareDialogStyleBottom);
		dialog.setContentView(view);
		dialog.show();
	}
	
	public final int SHAREFRIEND = 0;
	public final int SHARECIRCLE = 1;
	public final String APP_ID = "wx0d0a52aecd770a21";

	private void shareWX(String message, boolean isShareToFriends) {

		// 初始化一个WXTextObject对象
		WXTextObject textObj = new WXTextObject();
		textObj.text = message;

		// 用WXTextObject对象初始化一个WXMediaMessage对象
		WXMediaMessage msg = new WXMediaMessage();
		msg.mediaObject = textObj;
		// 发送文本类型的消息时，title字段不起作用
		// msg.title = "Will be ignored";
		msg.description = message;

		// 构造一个Req
		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("text"); // transaction字段用于唯一标识一个请求
		req.message = msg;
		req.scene = isShareToFriends ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
		
		// 调用api接口发送数据到微信
		iwxapi.sendReq(req);
	}
	
	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
	}
	
    /**
     * 用异步方式启动分享
     * @param params
     */
    private void doShareToQQ(final Bundle params) {
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                mQQShare.shareToQQ(activity, params, new IUiListener() {

                    @Override
                    public void onCancel() {
                    	
                    }

                    @Override
                    public void onComplete(Object response) {
                    	
                    }

                    @Override
                    public void onError(UiError e) {
                    	
                    }
                });
            }
        }).start();
    }
    
    /**
     * 用异步方式启动分享
     * @param params
     */
    private void doShareToQzone(final Bundle params) {
        new Thread(new Runnable() {
            
            @Override
            public void run() {
            	mTencent.shareToQzone(activity, params, new IUiListener() {

                    @Override
                    public void onCancel() {
                    	
                    }

                    @Override
                    public void onError(UiError e) {

                    }

					@Override
					public void onComplete(Object response) {
						
					}
                });
            }
        }).start();
    }
	
	private class TQQApiListener implements IUiListener {
		private String mScope = "all";
        private Boolean mNeedReAuth = false;
        private BaseActivity mActivity;
    	public TQQApiListener(String scope, boolean needReAuth,
				BaseActivity activity) {
			this.mScope = scope;
			this.mNeedReAuth = needReAuth;
			this.mActivity = activity;
		}

		@Override
		public void onComplete(Object response) {
			final BaseActivity activity = mActivity;
			try {
				JSONObject json =(JSONObject)response;
				int ret = json.getInt("ret");
				if (ret == 0) {
					Toast.show(activity, "发布微博成功！");
				} else if (ret == 100030) {
					if (mNeedReAuth) {
						Runnable r = new Runnable() {
							public void run() {
								mQQAuth.reAuth(activity,
										mScope, null);
							}
						};
						activity.runOnUiThread(r);
					}
				} else {
					Toast.show(activity, "发布微博失败！");
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onCancel() {
			System.out.println("onCancel");
		}

		@Override
		public void onError(UiError arg0) {
			System.out.println("onError");
		}
	}
	
	public boolean ready(Context context) {
		if (mQQAuth == null) {
			return false;
		}
		boolean ready = mQQAuth.isSessionValid()
				&& mQQAuth.getQQToken().getOpenId() != null;
//		if (!ready)
//			Toast.makeText(context, "login and get openId first, please!",
//					Toast.LENGTH_SHORT).show();
		return ready;
	}
	
	private void onClickLogin() {
		if (!mQQAuth.isSessionValid()) {
			IUiListener listener = new IUiListener() {
				@Override
				public void onCancel() {
					
				}

				@Override
				public void onComplete(Object arg0) {
//					Toast.show(activity, "QQ授权成功！");
					String content = "test add tweet";
					mWeibo.sendText(content, new TQQApiListener("add_t", false, activity));
				}

				@Override
				public void onError(UiError arg0) {
					Toast.show(activity, "QQ授权失败！");
				}
			};
			mTencent.login(activity, "all", listener);
		} else {
			mQQAuth.logout(activity);
		}
	}
	
	@Override
	public void onClick(View v) {
		final Bundle params = new Bundle();
		switch (v.getId()) {
		case R.id.item_weixin:
			shareWX(msg, true);
			dialog.dismiss();
			break;
		case R.id.item_qq:
        	params.putString(QQShare.SHARE_TO_QQ_TITLE, "常熟本地app");
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, "http://www.baidu.com");
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "沃手出品，牛逼啊");
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "http://imgcache.qq.com/music/photo/mid_album_300/V/E/000J1pJ50cDCVE.jpg");
            params.putString(QQShare.SHARE_TO_QQ_APP_NAME, activity.getResources().getString(R.string.app_name));
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
            params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, 0x00);
            
            doShareToQQ(params);
			dialog.dismiss();
			break;
		case R.id.item_qqzone:
            params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
            params.putString(QzoneShare.SHARE_TO_QQ_TITLE, "常熟本地app");
            params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, "沃手出品，牛逼啊");
            params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, "http://www.baidu.com");
            // 支持传多个imageUrl
            ArrayList<String> imageUrls = new ArrayList<String>();
            imageUrls.add("http://imgcache.qq.com/music/photo/mid_album_300/V/E/000J1pJ50cDCVE.jpg");
            params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);
            doShareToQzone(params);
			
			dialog.dismiss();
			break;
		case R.id.item_friends:
			int wxSdkVersion = iwxapi.getWXAppSupportAPI();
			if (wxSdkVersion < TIMELINE_SUPPORTED_VERSION) {
				Toast.show(activity, "您的微信不支持分享到朋友圈，请下载并安装最新版本后重试！");
				dialog.dismiss();
				break;
			}
			shareWX(msg, false);
			dialog.dismiss();
			break;
		case R.id.item_weibo:
			if (ready(activity)) {
				String content = "test add tweet";
				mWeibo.sendText(content, new TQQApiListener("add_t", false, activity));
			} else {
				onClickLogin();
			}
			dialog.dismiss();
			break;
		case R.id.btn_cancel:
			dialog.dismiss();
			break;
		default:
			break;
		}
	}
}
